package com.fly.core.exception;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.show.model.JsonResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 统一异常处理器
 * 
 * @author 00fly
 * @version [版本号, 2018-09-11]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Deprecated
@Slf4j
//@Component
public class ExceptionHandler implements HandlerExceptionResolver
{
    private ObjectMapper mapper = new ObjectMapper();
    
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
    {
        log.error(handler.toString(), exception);
        try
        {
            // JSR303参数校验异常(处理不完善)
            if (exception instanceof BindException)
            {
                BindingResult bindingResult = ((BindException)exception).getBindingResult();
                if (null != bindingResult && bindingResult.hasErrors())
                {
                    List<String> errMsg = new ArrayList<>();
                    bindingResult.getFieldErrors().stream().forEach(fieldError -> {
                        errMsg.add(fieldError.getDefaultMessage());
                    });
                    JsonResult<?> result = JsonResult.error(StringUtils.join(errMsg, ","));
                    response.getWriter().write(mapper.writeValueAsString(result));
                    return new ModelAndView();
                }
            }
            
            // 手动抛出的ValidateException
            if (exception instanceof ValidateException)
            {
                // 设置ContentType
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                // 避免乱码
                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                response.setHeader("Cache-Control", "no-cache, must-revalidate");
                JsonResult<?> result = JsonResult.error(exception.getMessage());
                response.getWriter().write(mapper.writeValueAsString(result));
                return new ModelAndView();
            }
        }
        catch (IOException ex)
        {
            log.error(ex.getMessage(), ex);
        }
        // 非ajax请求返回提示页
        request.setAttribute("ex", exception);
        return new ModelAndView("/error");
    }
    
    /**
     * 判断一个请求是否是Ajax请求
     * 
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean isAjaxRequest(HttpServletRequest request)
    {
        return request != null && "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
    }
}
